package com.ruoyi.api.kehu.order;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.github.pagehelper.PageHelper;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.RefundModel;
import com.ruoyi.api.kehu.dto.PayOrderCreateRespVo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.pay.WxPayXiaoChengXuConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DistanceUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.mapIp.MapPoint;
import com.ruoyi.common.utils.mapIp.MapPointUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.OrderUtil;
import com.ruoyi.system.utils.ProfileUtil;
import com.ruoyi.system.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/kehu/order")
@Api(tags = "用户订单相关接口")
public class ApiOrderController {

    private static final Logger logger = LoggerFactory.getLogger(ApiOrderController.class);

    @Autowired
    private IJiajiaOrderService orderService;

    @Autowired
    private IJiajiaOrderTimeService orderTimeService;

    @Autowired
    private IJiajiaWorkerService workerService;

    @Autowired
    private IJiajiaItemService itemService;

    @Autowired
    private IJiajiaWorkerItemService workerItemService;

    @Autowired
    private IJiajiaCouponService couponService;

    @Autowired
    private IJiajiaUserCouponService userCouponService;

    @Autowired
    private IJiajiaUserService userService;

    @Autowired
    private IJiajiaCityService cityService;

    @Autowired
    private IJiajiaWorkerJiedanService jiedanService;

    @Autowired
    private IJiajiaWorkerJiedanDetailService jiedanDetailService;

    @Autowired
    private IJiajiaMessageService messageService;

    @Autowired
    private IJiajiaUserMoneyChangeService moneyChangeService;

    @Autowired
    private IJiajiaWorkerTimeXxConfigService timeXxConfigService;
    @Autowired
    private IJiajiaMappointsService jiajiaMappointsService;
    @Autowired
    private IJiajiaAppraiseService appraiseService;

    @Autowired
    private WxPayXiaoChengXuConfig xiaoChengXuConfig;


    @Autowired
    private ISysDeptService sysDeptService;
    //APPID
    public static final  String app_id = "2021002193607091";
    //私钥
    public static final  String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCY1D1gQWUsrT4mZ2mBBK4tAFYK0ecSI1IE2MenSdrYwRdMETLtgog8mxDGgX5mHvbGVwrYpODx8SMvCScCpyCFlaRB1HWZrv7ny1XJOk+Xd6E7xbtzV3qWPq31Sl5qmQDRcSHhz7e6kRZiOAqR0AWYgRKccbocAZeoodsv0oriKQql+utEOURW/MAzEBrXKW9CD94EgPB6ByT077uJf9mDJTiR++AV48aj6iQZyU6+Va968urhihr0Hr3c3KkZrA7Wcs35RHOguhEtfsECt5fK/UQZDUYJP+5+2LjB93AqLsioopWa6Nusu5W3k6aqK32yG9/QreaOP1OitGIdviH7AgMBAAECggEABUzvKAR8ntUPX8OcbCYeaF8nnM505jMlaBegrROprHTd+vxpuMUbNobmSQw6tw4B3xUrwiHNz3ZekwYNPVFQlnF/Ne1JeuAP5TgvLICCPC2hAPK1sqVpEgbwf55psebGmX0EANH0fFsF3Lg23aHKX+SyIYzsOIZxnR6n/Huf54IZLPLRoHvkpxXVHWiEOsBTkijjy4OQsx+vjPbxx/awc9DMXQjUbM4kASLZS5cg73xLl7topxkebsLm8tHihUUP7wSU1wpfWeBACp63LH3LfkwqAf+YgvKpiAC2fGKzDOvYM71kGS/lzTJfve/MJKsDRUyg6H7eMXf6Lu423irSEQKBgQDGoBu88dtg8UhteTi6FV7NRzwlza0y88RUA2c0+oog1vv9jT4195E7WQnOAGeX2qF7gz8Z8R8Uf05PVhWVg0xPNp2m/7N/5wFkwI0zhCrFgoHqr1AYK9V77UgiB8xGeVZVXYgSjYgL1HEW4VUm9ie1LV3I3AdbRBOqUJAQZV7kiQKBgQDE+ZicqV5SyYyn9QMBVQtbTug5A23KD5804e9h2kEFih6fnOCjvWZjR2bDhcsS1gzUy4161d0rL5+yeLfVZnEuxxTNXeR6D5ZxwwR/R7Ra436Uv7e3NT6xyjA88+zU0CrhCdN2fFDR+WInZ1vipkG8GC6UhSzxSpoTFmexTA95YwKBgQC3l8yr1B6EN+JLlk3x6sjrE9or0zYxr5KcWVzvYlmEy1K25fRH6+KpKb7fVA5tFaBHy2PrNa4Vwyp+OMLQpUFGwuPsNdQT+FGYcEbUBGmIkP5HD+8HuJSm7QfMtMqDpapAU6jwBTRoQuCZVoTf8412cU2L2J1QJdfLiJXxIdIZiQKBgQCAUCe+RgaP34OlFdJzV7ciL/DO0xD+A9cuV8/c6pRYy3TPfR5JC+Ra3/RtggabqpyJMmBjmFWPAGMDm+gFN8qbMky2y2c+rFDQor2XPFqcqn2W4J0I18KThqaNzkiFCWYlWoVKNglf/xiVmpsctjk0Enyle2ufc32S2ZGKyYV7CQKBgAWtLSpozvvStYoZXUcM/d3TxRrAwiH5Z9j+SEkyuwIAHHzAM/5CNX1F7eBwvBHUEbe/ovpkV5hYrtJJFooXAHYAjnKOifrGSLTCJk8JcHbOpW7FJyaN/mgqAOS2+BEL20ni+/DCo7k04r0n98fAiSIyXicRFbB5LQbHQLUKQAKg";
    //支付宝公钥
    public static final  String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjKAfHxCHiGgBMZdZQlfjsXj3s5/xYevKjGMnkLI5+JqRVGlDi6GSyMM15r80uZ112BHQgjrm0O/AFrDA6BttOzSVKK+8biicwBXHs2SytPfq2FyZIAAaMaPHB527UFK5I4XmMRycLR1nwPiWL/y9PWOYtwTRJIpG2CpCV0ypZz+Bebf9IdrN3WQPpCUdS3RUDr4PDa1WiYCuycb9txywCEkSaBsf+9xRzxX0SQFgJDhKnGR3JRPBUN+W1KdS0j2Bpev6p9Ew+X28QTlYig6asuPVyZKyZKD33xYqOuIwIijDXYkNTWRsGFpO0fU+EkAQ8F01seei+/rZTO4gJ1kZ0QIDAQAB";
    //网关地址
    public static final  String gatewayUrl = "https://openapi.alipay.com/gateway.do";



    @ApiOperation("订单列表")
    @PostMapping("/orderList")
    public AjaxResult orderList(@RequestParam @ApiParam(value = "0 全部订单 1 进行中 2 待评价 3 取消") Integer type,
                                @RequestParam Integer pageNo,
                                @RequestParam Integer pageSize){

        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();

        JiajiaOrder order =  new JiajiaOrder();
        order.setUid(TokenUtil.getUid());
        order.getParams().put("type",type);
        PageHelper.startPage(pageNo,pageSize,"addtime desc");
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        for (JiajiaOrder model : orderList) {
            JiajiaOrderTime jiajiaOrderTime = new JiajiaOrderTime();
            jiajiaOrderTime.setOrderSn(model.getOrderSn());
            List<JiajiaOrderTime> orderTimeList = orderTimeService.selectJiajiaOrderTimeList(jiajiaOrderTime);
            if (ObjectUtil.isNotEmpty(orderTimeList)) {
                model.setOrderTimeList(orderTimeList);
            }
            if(model.getStatus().intValue() == 0){
                model.getParams().put("statusDes","待支付");
            }
            if(model.getStatus().intValue() == 1){
                model.getParams().put("statusDes","社工确认中");
            }
            if(model.getStatus().intValue() == 2){
                model.getParams().put("statusDes","社工已接单");
            }
            if(model.getStatus().intValue() == 3){
                model.getParams().put("statusDes","社工出发");
            }
            if(model.getStatus().intValue() == 4){
                model.getParams().put("statusDes","社工到达");
            }
            if(model.getStatus().intValue() == 5){
                model.getParams().put("statusDes","社工服务中");
            }
            if(model.getStatus().intValue() == 6){
                model.getParams().put("statusDes","服务完成待确认");
            }
            if(model.getStatus().intValue() == 7){
                model.getParams().put("statusDes","取消服务");
            }
            if(model.getStatus().intValue() == 8){
                model.getParams().put("statusDes","社工拒绝接单");
            }
            if(model.getStatus().intValue() == 9){
                model.getParams().put("statusDes","服务已完成");
            }

            if(model.getIsShouHou().intValue() == 1){
                model.getParams().put("statusDes","服务完成(正在售后)");
            }
        }

       return AjaxResult.success(orderList);
    }

    @ApiOperation(value = "订单详情接口")
    @PostMapping("/orderDetail")
    public AjaxResult orderDetail(@RequestParam @ApiParam(value = "订单ID") Long id){


        JSONObject resObj = new JSONObject();

        JiajiaOrder order= orderService.selectJiajiaOrderById(id);
        resObj.put("order",order);

        //查询社工定位
        JiajiaWorker worker = workerService.selectJiajiaWorkerById(order.getWid());
        resObj.put("lat",worker.getLat());
        resObj.put("lng",worker.getLng());
        resObj.put("pingJia","");

        if (order.getIsPingJia().intValue() == 1){
            JiajiaAppraise appraise = new JiajiaAppraise();
            appraise.setOid(order.getId());
            List<JiajiaAppraise> appraiseList = appraiseService.selectJiajiaAppraiseList(appraise);
            resObj.put("pingJia",appraiseList.get(0));
        }
        JiajiaOrderTime orderTime = new JiajiaOrderTime();
        orderTime.setOrderSn(order.getOrderSn());
        List<JiajiaOrderTime> jiajiaOrderTimes = orderTimeService.selectJiajiaOrderTimeList(orderTime);
        resObj.put("orderTimeList",jiajiaOrderTimes);
        return AjaxResult.success(resObj);
    }


    @ApiOperation(value = "创建订单")
    @PostMapping("/createOrder")
    @Transactional
    public AjaxResult createOrder(@RequestParam Long wid,
                                  @RequestParam Long iid,
                                  @RequestParam Integer chuXing,
                                  @RequestParam Float chuXingPrice,
                                  @RequestParam(required = false)Long cid,
                                  @RequestParam String yuYueTime,
                                  @RequestParam(required = false)String note,
                                  @RequestParam String address,
                                  @RequestParam String addressDes,
                                  @RequestParam String lat,
                                  @RequestParam String lng,
                                  @RequestParam Integer payType,
                                  @RequestParam String typeCode,
                                  @RequestParam(required = false) @ApiParam(value = "医院或社区ID") Long hid,
                                  @RequestParam(required = false) @ApiParam(value = "科室ID") Long hdid,
                                  @RequestParam(required = false) @ApiParam(value = "床号") String bedNum,
                                  @RequestParam @ApiParam(value = "被社工人名称") String beCareName,
                                  @RequestParam @ApiParam(value = "联系人电话") String tel,
                                  @RequestParam @ApiParam(value = "联系人") String name,
                                  @RequestParam(required = false) @ApiParam(value = "保姆月数") Integer nannyMonth){

        JiajiaOrder order = new JiajiaOrder();

        JiajiaWorker worker = workerService.selectJiajiaWorkerById(wid);
        if (worker == null)return AjaxResult.refreshAgain();

        if (worker.getCodeAuth().intValue() != 1){
            return AjaxResult.error("当前社工暂未身份认证，请重新选择社工");
        }

        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();


        String cityName = TokenUtil.getQuByLocation();

        JiajiaActivateCity city = new JiajiaActivateCity();
        city.setName(cityName);
        List<JiajiaActivateCity> cityList = cityService.selectJiajiaCityList(city);
        if (cityList.isEmpty()){
            return AjaxResult.error("暂未开放"+cityName+"的服务，如有需要，请联系客服！");
        }
        //判断订单归属区域
        String adcodeBylatlon = TokenUtil.getAdcodeBylatlon(lat, lng);
        logger.info("adcodeBylatlon:"+adcodeBylatlon);
        SysDept sysDept = sysDeptService.selectDeptByAdcode(adcodeBylatlon);
        if(!Optional.ofNullable(sysDept).isPresent()){
            return AjaxResult.error("暂未开放该区域的服务，如有需要，请联系客服！");

        }
        //先入区域,小区有代理再覆盖
        order.setDeptId(sysDept.getDeptId());

        //订单归属小区
        SysDept sysDeptChild=new  SysDept();
        sysDeptChild.setParentId(sysDept.getDeptId());
        //该区域下所有小区
        List<SysDept> sysDepts = sysDeptService.selectDeptList(sysDeptChild);
        if(Optional.ofNullable(sysDepts).isPresent() && sysDepts.size()>0){
            for (SysDept sysDeptChilds:sysDepts) {
                JiajiaMappoints jiajiaMappoints=new JiajiaMappoints();
                jiajiaMappoints.setDeptId(sysDeptChilds.getDeptId());
                List<JiajiaMappoints> jiajiaMappoints1 = jiajiaMappointsService.selectJiajiaMappointsList(jiajiaMappoints);
                if (jiajiaMappoints1.isEmpty()){
                    continue;
                }
                MapPoint mapPoint=new MapPoint(Double.valueOf(TokenUtil.getLat()),Double.valueOf(TokenUtil.getLng()));
                List<MapPoint> collect1 = jiajiaMappoints1.stream().map(jiajiaMappointsMap -> {
                    MapPoint mapPoints = new MapPoint(Double.valueOf(jiajiaMappointsMap.getLatitude()), Double.valueOf(jiajiaMappointsMap.getLongitude()));
                    return mapPoints;
                }).collect(Collectors.toList());
                MapPoint[] mapPoints=new MapPoint[jiajiaMappoints1.size()];
                boolean pointInPolygon = MapPointUtils.isPointInPolygon(mapPoint, collect1.toArray(mapPoints));
                if(pointInPolygon){
                    user.setDeptId(sysDeptChilds.getDeptId());
                }
            }

        }

        List<JiajiaOrderTime> orderTimes = Lists.newArrayList();
        if (!(typeCode.equals("nanny_service"))){
            //判断预约时间与社工是否冲突
            //验证此时段社工是否能下单
            //先查询休息  再查询订单
            //Date yyStartTime =  DateUtils.parseDate(yuYueStartTime);
            if (StringUtils.isEmpty(yuYueTime))return AjaxResult.error("未选择预约时间");

            JSONArray yyTimeJson = JSONArray.parseArray(yuYueTime);
            for(int i=0;i<yyTimeJson.size();i++){

                JSONObject rowDayObj = yyTimeJson.getJSONObject(i);
                String day = Convert.toStr(rowDayObj.get("day"));
                JSONArray timeArray = rowDayObj.getJSONArray("timeList");
                logger.info(">>>>timeArray>>>"+timeArray.toJSONString());
                if(timeArray == null || timeArray.size() <= 0){
                    return AjaxResult.error("预约失败：请选择预约时间！");
                }
                for(int k=0;k<timeArray.size();k++){
                    JSONObject rowTimeObj = timeArray.getJSONObject(k);
                    String startTime = Convert.toStr(rowTimeObj.get("startTime"));
                    String endTime = Convert.toStr(rowTimeObj.get("endTime"));
                    Long tcId = Convert.toLong(rowTimeObj.get("id"));
                    JiajiaOrderTime orderTime = new JiajiaOrderTime();
                    orderTime.setTcid(tcId);
                    orderTime.setDay(day);
                    orderTime.setStartTime(startTime);
                    orderTime.setEndTime(endTime);
                    orderTime.setUid(TokenUtil.getUid());
                    orderTime.setIid(iid);
                    orderTime.setWid(wid);
                    orderTimes.add(orderTime);

                    JiajiaWorkerTimeXxConfig restConfig = new JiajiaWorkerTimeXxConfig();
                    restConfig.setWid(wid);
                    restConfig.setDay(day);
                    restConfig.setStatus(0);
                    restConfig.setStartime(startTime);
                    restConfig.setEndtime(endTime);
                    List<JiajiaWorkerTimeXxConfig> timeXxConfigs = timeXxConfigService.selectTimeXxConfigList(restConfig);
                    if(ObjectUtil.isNotEmpty(timeXxConfigs)){
                        return AjaxResult.error("预约失败：["+day+","+startTime+"-"+endTime+"]时段社工休息！");
                    }
                }
            }
        }



        JiajiaWorkerItem workerItem = new JiajiaWorkerItem();
        workerItem.setIid(iid);
        workerItem.setWid(wid);
        List<JiajiaWorkerItem> workerItemList = workerItemService.selectJiajiaWorkerItemList(workerItem);

        if (workerItemList.isEmpty()){
            return AjaxResult.error("此社工暂未上架此项服务");
        }

        JiajiaItem item = itemService.selectJiajiaItemById(iid);
        if (item == null)return AjaxResult.refreshAgain();




        float youHuiPrice = 0;

        JiajiaUserCoupon userCoupon = null;
        if (cid != null && cid > 0){
            userCoupon = userCouponService.selectJiajiaUserCouponById(cid);
            if (userCoupon == null){
                return AjaxResult.error("优惠券使用失败");
            }
            if (userCoupon.getStatus().intValue() != 0){
                return AjaxResult.error("优惠券使用失败");
            }
            if (userCoupon.getSxTime().before(new Date())){
                return AjaxResult.error("优惠券已失效");
            }
            if (item.getDisPrice().floatValue() < userCoupon.getTiaoJian().floatValue()){
                return AjaxResult.error("不满足优惠券条件");
            }
            youHuiPrice = userCoupon.getPrice().floatValue();

            userCoupon.setStatus(1);
            userCoupon.setSyTime(new Date());
            order.setCouponId(cid);
        }


        //选择项目总金额=项目单价X选择的班次数量
        BigDecimal itemTotalAmount = item.getDisPrice().multiply(BigDecimal.valueOf(orderTimes.size()));
        //支付总费用
        float totalPrice = itemTotalAmount.floatValue() + chuXingPrice.floatValue() - youHuiPrice;

        if (payType == 0){
            if (Convert.toBigDecimal(user.getMoney(), BigDecimal.ZERO).floatValue() < totalPrice){
                return AjaxResult.error("余额不足，请选择其他支付方式");
            }
        }
        if (ObjectUtil.isNotNull(nannyMonth)){
            order.setNannyMonth(nannyMonth);
        }
        order.setItemTypeCode(item.getTypeCode());
        order.setHid(hid);
        order.setHdid(hdid);
        order.setBedNum(bedNum);
        order.setBeCareName(beCareName);
        order.setTotalPrice(new BigDecimal(totalPrice));
        order.setYouHuiPrice(new BigDecimal(youHuiPrice));
        order.setChuXingPrice(new BigDecimal(chuXingPrice));
        order.setItemPrice(item.getDisPrice());
        order.setRealPrice(new BigDecimal(totalPrice));
        order.setChuXing(chuXing);
        order.setNote(note);
        order.setAddress(address);
        order.setAddressDes(address+addressDes);
        order.setPayType(payType);
        order.setLat(lat);
        order.setLng(lng);
        order.setUid(TokenUtil.getUid());
        order.setIid(iid);
        order.setWid(wid);
        order.setCityId(cityList.get(0).getId().intValue());

        order.setTel(tel);
        order.setName(name);
        order.setTimeSpan(item.getTimeSpan());

        Random random = new Random();
        String orderSn = System.currentTimeMillis()/1000+""+(random.nextInt(8999)+1000);
        order.setOrderSn(orderSn);



        //余额支付
        if (payType.intValue() == 0){

            JiajiaUserMoneyChange moneyChange = new JiajiaUserMoneyChange();
            moneyChange.setChangeBefore(user.getMoney());

            order.setStatus(1);
            user.setMoney(new BigDecimal(user.getMoney().floatValue() - order.getRealPrice().floatValue()));
            userService.updateJiajiaUser(user);

            moneyChange.setChangeAfter(user.getMoney());
            moneyChange.setChangeMoney(new BigDecimal( - order.getRealPrice().floatValue()));
            moneyChange.setType("订单支付成功");
            moneyChange.setDes("用户下单(余额支付)");
            moneyChange.setOtherId(order.getOrderSn());
            moneyChange.setUid(order.getUid());
            moneyChangeService.insertJiajiaUserMoneyChange(moneyChange);

            //创建通知
            JiajiaMessage message = new JiajiaMessage();
            message.setType(1);
            message.setTitle("客户已下单");
            message.setContent("请尽快接单");
            message.setUid(wid);
            messageService.insertJiajiaMessage(message);

            //创建通知
            JiajiaMessage userMessage = new JiajiaMessage();
            userMessage.setType(2);
            userMessage.setTitle("下单成功");
            userMessage.setContent("下单成功,等待社工接单!");
            userMessage.setUid(user.getId());
            messageService.insertJiajiaMessage(userMessage);
        }

        if (userCoupon != null){
            userCouponService.updateJiajiaUserCoupon(userCoupon);
        }

        orderService.insertJiajiaOrder(order);

        //保存预约时间
        if(ObjectUtil.isNotEmpty(orderTimes)){
            orderTimes.forEach(rowVal -> {
                rowVal.setOrderSn(order.getOrderSn());
                orderTimeService.insertJiajiaOrderTime(rowVal);
            });
        }

        PayOrderCreateRespVo createRespVo = new PayOrderCreateRespVo();
        createRespVo.setOrderSn(order.getOrderSn());
        createRespVo.setOrderTimeList(orderTimes);
        return AjaxResult.success("创建成功", createRespVo);
    }

    @ApiOperation("取消订单")
    @PostMapping("/cancelOrder")
    @Transactional
    public AjaxResult cancelOrder(@RequestParam @ApiParam(value = "订单号") String orderSn,
                                  @RequestParam @ApiParam(value = "取消原因") String cancelNotes,
                                  @RequestParam(required = false) @ApiParam(value = "取消备注") String cancelContent,
                                  @RequestParam(required = false) @ApiParam(value = "取消订单图片") String cancelUrls
    ) throws Exception {

        JiajiaOrder order = new JiajiaOrder();
        order.setOrderSn(orderSn);
        List<JiajiaOrder> orders = orderService.selectJiajiaOrderList(order);
        if (orders.isEmpty()) return AjaxResult.error("订单不存在");
        order = orders.get(0);

        if (order.getCancelStatus().intValue() == 1){
            return AjaxResult.error("此订单已退款");
        }

        if (order.getStatus().intValue() == 0){
            order.setStatus(7);
            orderService.updateJiajiaOrder(order);
            return AjaxResult.success("取消成功");
        }

        if (order.getStatus().intValue() >= 3){
            return AjaxResult.error("当前状态不能取消订单");
        }

        JiajiaUser user = userService.selectJiajiaUserById(order.getUid());

        order.setCancelNote(cancelNotes);
        order.setCancelContent(cancelContent);
        order.setCancelUrls(cancelUrls);

        //创建通知
        JiajiaMessage message = new JiajiaMessage();
        message.setType(1);
        message.setTitle("客户已取消订单");
        message.setContent("客户已取消订单");
        message.setUid(order.getWid());
        messageService.insertJiajiaMessage(message);

        //创建通知
        JiajiaMessage userMessage = new JiajiaMessage();
        userMessage.setType(2);
        userMessage.setTitle("取消订单");
        userMessage.setContent("订单取消成功");
        userMessage.setUid(order.getUid());
        messageService.insertJiajiaMessage(userMessage);

        order.setCancelStatus(1);
        order.setCanceltime(new Date());
        order.setStatus(7);
        orderService.updateJiajiaOrder(order);

        //退还客户余额
        if (order.getPayType().intValue() == 0){
            JiajiaUserMoneyChange moneyChange = new JiajiaUserMoneyChange();
            moneyChange.setChangeBefore(user.getMoney());

            user.setMoney(new BigDecimal(user.getMoney().floatValue()+order.getRealPrice().floatValue()));
            userService.updateJiajiaUser(user);

            moneyChange.setChangeAfter(user.getMoney());
            moneyChange.setChangeMoney(order.getRealPrice());
            moneyChange.setType("订单取消");
            moneyChange.setDes("用户取消订单，返还金额");
            moneyChange.setOtherId(order.getOrderSn());
            moneyChange.setUid(order.getUid());
            moneyChangeService.insertJiajiaUserMoneyChange(moneyChange);
        }

        //小程序支付退款
        if (order.getPayType().intValue() == 3 && order.getPayStatus().intValue() == 1 ){
            String tuiMoney = String.valueOf((order.getRealPrice().multiply(new BigDecimal("100"))).intValue());

            //这里是走小程序退款
            Map<String, String> params = RefundModel.builder()
                    .appid(xiaoChengXuConfig.getAppid())
                    .mch_id(xiaoChengXuConfig.getMachid())
                    .nonce_str(WxPayKit.generateStr())
                    .out_trade_no(orderSn)
                    .out_refund_no(orderSn)
                    .total_fee(tuiMoney)
                    .refund_fee(tuiMoney)
                    .notify_url(xiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/refundNotify")
                    .build()
                    .createSign(xiaoChengXuConfig.getMckKey(), SignType.MD5);
            InputStream certIs = null;
            try {
                ClassPathResource classPathResource = new ClassPathResource(xiaoChengXuConfig.getKeyPath());
                certIs = classPathResource.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
           String a = WxPayApi.orderRefundByProtocol(false, params, certIs, xiaoChengXuConfig.getMachid(), "");
           Map<String,String> map = WxPayKit.xmlToMap(a);
           String returnCode = map.get("return_code");
           String resultCode = map.get("result_code");
           if (!resultCode.equals("SUCCESS") || !returnCode.equals("SUCCESS")){
               throw new RuntimeException("退款失败");
           }

        }

        //微信退款
        if (order.getPayType().intValue() == 1 && order.getPayStatus().intValue() == 1 ) {
            String tuiMoney = String.valueOf((order.getRealPrice().multiply(new BigDecimal("100"))).intValue());
            if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV)) {
                tuiMoney = "1";
            }
            Map<String, String> params = RefundModel.builder()
                    .appid(xiaoChengXuConfig.getAppid())
                    .mch_id(xiaoChengXuConfig.getMachid())
                    .nonce_str(WxPayKit.generateStr())
                    .out_trade_no(orderSn)
                    .out_refund_no(orderSn)
                    .total_fee(tuiMoney)
                    .refund_fee(tuiMoney)
                    .notify_url(xiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/wxRefundNotify")
                    .build()
                    .createSign(xiaoChengXuConfig.getMckKey(), SignType.MD5);
            InputStream certIs = null;
            try {
                ClassPathResource classPathResource = new ClassPathResource(xiaoChengXuConfig.getKeyPath());
                certIs = classPathResource.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String a = WxPayApi.orderRefundByProtocol(false, params, certIs, xiaoChengXuConfig.getMachid(), "");
            Map<String,String> map = WxPayKit.xmlToMap(a);
            String returnCode = map.get("return_code");
            String resultCode = map.get("result_code");
            if (!resultCode.equals("SUCCESS") || !returnCode.equals("SUCCESS")){
                throw new RuntimeException("退款失败");
            }

        }

        //支付宝退款
        if (order.getPayType().intValue() == 2 && order.getPayStatus().intValue() == 1 ) {

            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest (); //创建API对应的request类
            float payMoney = order.getRealPrice().floatValue();
            if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV)){
                payMoney = 0.01f;
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("out_trade_no",order.getOrderSn());
            jsonObject.put("refund_amount",payMoney);
            request.setBizContent(jsonObject.toJSONString());
            try {
                AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                        app_id,
                        merchant_private_key,
                        "json",
                        "utf-8",
                        alipay_public_key,
                        "RSA2");
                AlipayTradeRefundResponse response   =  alipayClient.execute(request); //通过alipayClient调用API，获得对应的response类
                return AjaxResult.success("",response.getBody());
            } catch (AlipayApiException e) {
                e.printStackTrace();
                return AjaxResult.error("支付宝取消失败"+e.toString());
            }

        }


        return AjaxResult.success("取消成功");
    }


    @ApiOperation("获取能下单的时间")
    @PostMapping("getCanYueTime")
    public AjaxResult getCanYueTime(@RequestParam Long wid){

        JiajiaWorker worker = workerService.selectJiajiaWorkerById(wid);
        if (worker == null)return AjaxResult.refreshAgain();

        JiajiaOrder order = new JiajiaOrder();
        order.getParams().put("yuYueTime", DateUtils.dateTime(new Date()));
        order.getParams().put("type","1");
        order.setWid(worker.getId());
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        JiajiaWorkerJiedan jiedan = new JiajiaWorkerJiedan();
        jiedan.setWid(worker.getId());
        jiedan.getParams().put("time",DateUtils.dateTime(new Date()));
        List<JiajiaWorkerJiedan> jiedanList = jiedanService.selectJiajiaWorkerJiedanList(jiedan);

        JiajiaWorkerJiedanDetail detail = new JiajiaWorkerJiedanDetail();
        detail.setWid(worker.getId());
        detail.getParams().put("jdIdsArr", StringUtils.listsToSbStr(jiedanList,"id").split(","));
        List<JiajiaWorkerJiedanDetail> detailList = jiedanDetailService.selectJiajiaWorkerJiedanDetailList(detail);


        return AjaxResult.success(OrderUtil.getCanYueList(worker,orderList,jiedanList,detailList));
    }


    /**计算费用*/
    @ApiOperation("计算出租费用")
    @PostMapping("getChuZuMoney")
    public AjaxResult getChuZuMoney(@RequestParam String lat,
                                    @RequestParam String lng,
                                    @RequestParam Long wid){

        JiajiaWorker worker = workerService.selectJiajiaWorkerById(wid);
        if (worker == null)return AjaxResult.refreshAgain();


        String key = "4d9e007da80609f238ca096e6cce2591";
        String destination = lng+","+lat;
        String origin = worker.getLng()+","+worker.getLat();
        String a = "key="+key+"&origin="+origin+"&destination="+destination+"&city=重庆市";
        String rspStr = HttpUtils.sendGet("https://restapi.amap.com/v3/direction/transit/integrated",a);

        JSONObject obj = JSONObject.parseObject(rspStr);

        int taxi = 0;
        float bus = 2f;

        JSONObject resObj = new JSONObject();
        resObj.put("taxi",taxi);
        resObj.put("bus",bus);

        if (obj.getIntValue("status") == 0){
            return AjaxResult.success(resObj);
        }
        JSONObject object =  obj.getJSONObject("route");
        taxi =  object.getIntValue("taxi_cost");
        if (taxi <= 0)taxi = 50;
        JSONArray jsonArray = object.getJSONArray("transits");

        if (jsonArray.size() > 0){
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if(jsonObject.get("cost")!= null){
                    if (jsonObject.getFloat("cost") > bus){
                        bus = jsonObject.getFloatValue("cost");
                    }
                }
            }
        }

        resObj.put("juLi", new BigDecimal(DistanceUtil.getDistance(lng,lat,worker.getLng(),worker.getLat())/1000).setScale(2, RoundingMode.HALF_UP));
        resObj.put("taxi",taxi);
        resObj.put("bus",bus);

        return AjaxResult.success(resObj);
    }

    @ApiOperation("获取未使用的优惠券")
    @PostMapping("getNotUseCoupon")
    public AjaxResult getNotUseCoupon(){

        //查询客户未使用的优惠券
        JiajiaUserCoupon userCoupon = new JiajiaUserCoupon();
        userCoupon.getParams().put("notUse","true");
        userCoupon.setUid(TokenUtil.getUid());
        List<JiajiaUserCoupon> userCouponList = userCouponService.selectJiajiaUserCouponList(userCoupon);

        return AjaxResult.success(userCouponList);
    }


}
